package hydrap2p.gui.commands;

import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.*;

import hydrap2p.download.DownloadPriority;
import hydrap2p.download.Source;
import hydrap2p.gui.GUIDataHandler;
import hydrap2p.gui.GUIDownloadListing;
import hydrap2p.library.Range;

import javax.swing.JFileChooser;
import javax.swing.JOptionPane;

public class Cmd_FileTransferPanel_AddURLToDownloadQueue implements Command {

	@Override
	public void execute() {
		// Get a path
		// HTTP Test Case:  http://mirrors.easynews.com/linux/ubuntu/dists/lucid/Contents-amd64.gz
		// FTP Test Case:  ftp://ftp.freebsd.org/pub/FreeBSD/releases/i386/8.0-RELEASE/kernels/generic.aa
		String urlPath = JOptionPane.showInputDialog(null, "Enter the path to the file you would like to download.");
		
		if (urlPath == null) //user pressed cancel
		{
			return;
		}
		
		URL url;
		try {
			url = new URL(urlPath);
		} catch (MalformedURLException e1) {
			JOptionPane.showMessageDialog(null, "The URL entered is malformed or otherwise incorrect.");
			return;
		}
		
		// Check prerequisites
		if(url.getProtocol() == null){
			System.out.println("No protocol detected for the URL entered.");
			return;
		}
		if(url.getDefaultPort() < 0){
			System.out.println("No default port detected for the URL protocol.");
			return;
		}
		if(url.getHost() == null){
			System.out.println("No domain detected for the URL entered.");
			return;
		}
		
		String domain = url.getHost();
		System.out.println("Domain: " + domain);
		int port = url.getDefaultPort();
		System.out.println("Port: " + port);
		String protocol = url.getProtocol();
		System.out.println("Protocol: " + protocol);
		
		long size = 0;
		try {
			size = url.openConnection().getContentLength();
		} catch (IOException e) {
			JOptionPane.showMessageDialog(null, "No connection to the URL could be made.");
			return;
		}
		
		System.out.println("Size: " + size);
		String path = url.getPath();
		System.out.println("Path: " + path);
		
		// TODO Fix Source parameters
		Source source = new Source(domain, port, protocol, "", null, Arrays.asList(new Range(0, size)), null, null);
		Map<String, String> extras = new TreeMap<String, String>();
		extras.put("path", path);
		source.setExtra(extras);
		
		// JFileChooser
		JFileChooser chooser = new JFileChooser();
		boolean sel;
		File filePath = null;
		
		do{
			sel = true;
			chooser.setDialogTitle("Select destination for " + path.substring(path.lastIndexOf("/")+1));
			chooser.setCurrentDirectory(new File(GUIDataHandler.DOWNLOAD_PATH));
			chooser.setSelectedFile(new File(GUIDataHandler.DOWNLOAD_PATH + "/" + path.substring(path.lastIndexOf("/")+1)));
			chooser.setMultiSelectionEnabled(false);
			
			int status = chooser.showDialog(null,"Save");
			GUIDataHandler.DOWNLOAD_PATH = chooser.getCurrentDirectory().getPath();
			
			try{
				while(filePath == null){
					if(status == JFileChooser.CANCEL_OPTION){
						return;
					}
					if(status == JFileChooser.APPROVE_OPTION){
						if(chooser.getSelectedFile().exists()){
							JOptionPane.showMessageDialog(null, "The specified file already exists.\n\nPlease select a different filepath.");
							status = chooser.showDialog(null,"Save");
						}
					}
					filePath = chooser.getSelectedFile();
					// Check filepath
					if(filePath.getName().length() == 0){
						JOptionPane.showMessageDialog(null, "No filename entered.");
						filePath = null;
					}else if(filePath.getParent() == null){
						JOptionPane.showMessageDialog(null, "Invalid directory.");
						filePath = null;
					}
				}
				
			}catch(Exception ex){
				sel = false;
				
			}
		}while(!sel);
		
		System.out.println("File selected.");
		
		// Generate a download listing
		GUIDownloadListing gdl = new GUIDownloadListing(filePath.getName(), protocol, "(no associated hash)",
								GUIDownloadListing.PAUSED, filePath.getParent(), 1, 0, DownloadPriority.NORMAL, size, 0, 0);
		gdl.addContent(path.substring(path.lastIndexOf("/")+1));
		gdl.addSource(source);
		GUIDataHandler.getInstance().addToDownloadListing(gdl);
		
		System.out.println(getCommand());
		
	}

	@Override
	public String getCommand() {
		return this.getClass().getSimpleName();
	}

	@Override
	public void unexecute() {
		// TODO Auto-generated method stub

	}

}
